package com.corn.juc.coll;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2020/12/25 17:39
 */

public class UnsafeListDemo {

    public static void main(String[] args) {
//        unsafeListDemo();
        safeCollectionsDemo();
        System.out.println("===========================================");
        safeCopyOnWriteList();
    }

    /**
     * java.util.ConcurrentModificationException
     * at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
     * at java.util.ArrayList$Itr.next(ArrayList.java:851)
     * at java.util.AbstractCollection.toString(AbstractCollection.java:461)
     * at java.lang.String.valueOf(String.java:2994)
     * at java.io.PrintStream.println(PrintStream.java:821)
     * at com.corn.juc.coll.UnsafeListDemo$1.run(UnsafeListDemo.java:23)
     */
    private static void unsafeListDemo() {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread() {
                @Override
                public void run() {
                    list.add(new Random().nextInt(2000));
                    System.out.println(list);
                }
            }.start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
    }

    /**
     * 使用Collections集合工具类的 synchronizedList
     */
    private static void safeCollectionsDemo() {
        List<Integer> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 30; i++) {
            new Thread() {
                @Override
                public void run() {
                    list.add(new Random().nextInt(2000));
                    System.out.println(list);
                }
            }.start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
    }

    private static void safeCopyOnWriteList() {
        List<Integer> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread() {
                @Override
                public void run() {
                    list.add(new Random().nextInt(2000));
                    System.out.println(list);
                }
            }.start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
    }
}
